<?php
/**
 * Author:Arthur
 * Date:2013-1-31
 * File Name:reply_history.php
 * Email:kingarthurx@sina.cn
 */
	require ('../include/init.php');
	$method = $_GET['method'];
	global $view_file;
	
	if (empty ($method)) {
		$method = 'select';
	}
	if ($method === 'select') {
		getServerReply();
		select();
		$view_file = "reply_history.tpl";
	}

/**
 * 获取八优服务器内回复的内容
 */
function getServerReply(){
	$reply = new Reply();
	$replyArr = $reply->getUserApi("");
	if(!empty($replyArr->api_username)){
		//获取回复短信URL
		$url="http://sms.c8686.com/Api/BayouSmsApiEx.aspx?func=getreply&username=".$replyArr->api_username."&password=".$replyArr->api_password."&msgcount=300&encodetype=";
		$ch = curl_init();  
		curl_setopt($ch,CURLOPT_URL,$url);  
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);     
	   	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); 
	 	$content= curl_exec($ch);  
		curl_close($ch);
	}else{
		echo '<script type="text/javascript"> alert("请设置API的账号和密码.");</script>';
	}
	//解析平常的xml文件
	//$xml = simplexml_load_string($xml_string);
	//解析带有cdata 的xml 文件
	$xml = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
	if(count($xml->reply->msg) > 0){
	for($i = 0; $i < count($xml->reply->msg); $i++){
			$reply->company_id = $_SESSION['user']['customer']->company_id;
			$reply->clientid = $replyArr->api_username;
			$reply->mobile = $xml->reply->msg[$i]->mobile;
			$reply->destmobile = $xml->reply->msg[$i]->destmobile;
			$reply->content = $xml->reply->msg[$i]->content;
			$reply->time = $xml->reply->msg[$i]->time;
			$reply->msg_type = 2;
			/**
			 * 获取的回复内容插入到本地数据库
			 */
			$reply ->insertReply();
	}
  }
}


/**
 * 从本地数据库查询结果，返回到页面
 */
function select(){
		$reply = new Reply();
		if(isset($_GET['page']))
		{
		$pages = $_GET['page'];
		}
		else
		{
		$pages = 1;
		}
		$GLOBALS['pages'] = $pages;
		$page = new page($pages);
		$GLOBALS['page']=$page;
		$reply->company_id=$_SESSION['user']['customer']->company_id;
		$total =$reply->countReplyMessageHistory();
		$GLOBALS['page']->pageft($total,$GLOBALS['displaypg']);
		$item=$reply->selectReply();
		global $smarty;
		$smarty->assign("item", $item);
		$smarty->assign("nextpage",$GLOBALS['page']->getPagenav());
}
/**
 * 显示内容到tpl模板
 */
$smarty->display(admin_display($view_file));

